import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Select, message, Row, Col } from 'antd';
import type { User, UserCreateParams, UserUpdateParams } from '@/api/system';

const { Option } = Select;

interface UserFormProps {
  visible: boolean;
  user?: User | null;
  onSubmit: (values: UserCreateParams | UserUpdateParams) => void;
  onCancel: () => void;
}

const UserForm: React.FC<UserFormProps> = ({ visible, user, onSubmit, onCancel }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  // 模拟部门选项（实际项目中应该从API获取）
  const departmentOptions = [
    { label: '技术部', value: '1' },
    { label: '市场部', value: '2' },
    { label: '运营部', value: '3' },
    { label: '人事部', value: '4' },
    { label: '财务部', value: '5' },
  ];

  useEffect(() => {
    if (visible && user) {
      // 编辑模式，填充表单
      form.setFieldsValue({
        id: user.id,
        username: user.username,
        name: user.name,
        mobile: user.mobile,
        email: user.email,
        avatar: user.avatar,
        deptId: user.deptId,
        status: user.status,
        remark: user.remark,
      });
    } else if (visible && !user) {
      // 新增模式，重置表单
      form.resetFields();
    }
  }, [visible, user, form]);

  const handleSubmit = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();

      // 移除id字段（新增模式不需要）
      const { id, ...submitValues } = values;

      if (user) {
        // 编辑模式，需要包含id
        onSubmit({ ...submitValues, id: user.id });
      } else {
        // 新增模式，需要密码
        if (!submitValues.password) {
          message.error('请输入密码');
          return;
        }
        onSubmit(submitValues);
      }
    } catch (error) {
      // 表单验证失败
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title={user ? '编辑用户' : '新增用户'}
      open={visible}
      onOk={handleSubmit}
      onCancel={onCancel}
      confirmLoading={loading}
      width={800}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        style={{ marginTop: 24 }}
      >
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label="用户名"
              name="username"
              rules={[
                { required: true, message: '请输入用户名' },
                { min: 3, max: 20, message: '用户名长度为3-20个字符' },
                { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' },
              ]}
            >
              <Input placeholder="请输入用户名" disabled={!!user} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="姓名"
              name="name"
              rules={[
                { required: true, message: '请输入姓名' },
                { max: 20, message: '姓名最多20个字符' },
              ]}
            >
              <Input placeholder="请输入姓名" />
            </Form.Item>
          </Col>
        </Row>

        {!user && (
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="密码"
                name="password"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 6, max: 20, message: '密码长度为6-20个字符' },
                ]}
              >
                <Input.Password placeholder="请输入密码" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="确认密码"
                name="confirmPassword"
                dependencies={['password']}
                rules={[
                  { required: true, message: '请确认密码' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不一致'));
                    },
                  }),
                ]}
              >
                <Input.Password placeholder="请确认密码" />
              </Form.Item>
            </Col>
          </Row>
        )}

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label="手机号"
              name="mobile"
              rules={[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
              ]}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="邮箱"
              name="email"
              rules={[
                { type: 'email', message: '请输入正确的邮箱格式' },
              ]}
            >
              <Input placeholder="请输入邮箱" />
            </Form.Item>
          </Col>
        </Row>

        {/* 隐藏的id字段，用于编辑模式 */}
        {user && (
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>
        )}
      </Form>
    </Modal>
  );
};

export default UserForm;